﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using ggHD.Mail;

namespace ggHD.Data
{
    public class DbLogWriter //: ILogWriter
    {
        private readonly string _connStr;
        private SqlConnection _sqlConn;


        public DbLogWriter(string connStr)
        {
            _connStr = connStr;
            _connStr = connStr;
            InitializeDb();
        }

        private void InitializeDb()
        {
            _sqlConn = new SqlConnection(_connStr);
            using (var cmd = _sqlConn.CreateCommand())
                try
                {
                    _sqlConn.Open();
                    cmd.CommandText = @"if not exists(select 1 from sys.tables t
                                where t.name = 'SysLog')
                                  create table SysLog(
                                    Id int identity primary key,
                                    ActionDate datetime not null,
                                    Header nvarchar(512) null,
                                    Msg nvarchar(4000) not null,
                                    Module nvarchar(256) null)";

                    cmd.CommandType = System.Data.CommandType.Text;

                    cmd.ExecuteNonQuery();
                }
                finally
                {
                    _sqlConn.Close();
                }
        }

        public void WriteToDb(string hdr, string msg, string module)
        {
            using (var qry = new SqlCommand(
                "insert into SysLog( ActionDate, Header,Msg,Module) values(getdate(), @hdr, @msg,@module)",
                _sqlConn))
                try
                {
                    if (_sqlConn.State != System.Data.ConnectionState.Open)
                        _sqlConn.Open();

                        
                    qry.CommandType = System.Data.CommandType.Text;
                    qry.Parameters.AddRange(new[]
                    {
                        new SqlParameter("@hdr", hdr),
                        new SqlParameter("@msg", msg),
                        new SqlParameter("@module", module)
                    });

                    qry.ExecuteNonQuery();
                }
                catch (Exception ex)
                {

                }
        }

        public void WriteLine(Exception exception, string message)
        {
            WriteToDb(message + ": " + exception.GetType(), exception.Message + "\r\n" + exception.StackTrace, null);
        }

    }
}
